package org.sith.taskrunner.ejb.db.dao.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.interceptor.Interceptors;
import javax.persistence.Query;

import org.sith.taskrunner.api.user.Role;
import org.sith.taskrunner.api.user.User;
import org.sith.taskrunner.ejb.annotations.AllowedRoles;
import org.sith.taskrunner.ejb.db.dao.AbstractDAO;
import org.sith.taskrunner.ejb.db.dao.UserDAO;
import org.sith.taskrunner.ejb.db.entity.UserEntity;
import org.sith.taskrunner.ejb.interceptors.PermissionsChecker;
import org.sith.taskrunner.util.MD5;

@Stateless(name = "UserDAOService")
@Interceptors(PermissionsChecker.class)
public class UserDAOService extends AbstractDAO<UserEntity> implements UserDAO {

	public static final String SQL_FIND_BY_ = "from UserEntity user where ";

	@Override
	protected Class<UserEntity> getEnityClass() {
		return UserEntity.class;
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public User getUserByNameAndPassword(String usrName, String usrPass) {		
		Query query = persistenceContext
				.createQuery(SQL_FIND_BY_+"login=:login and password=:password");
		query.setParameter("login", usrName);
		query.setParameter("password", MD5.getHashCode(usrPass));
        UserEntity user = (UserEntity) query.getSingleResult();
		return user;
	}
	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public List<UserEntity> getUserByRole(Role role){
		Query query = persistenceContext.createQuery(SQL_FIND_BY_+"role=:role");
		query.setParameter("role", role);
		List<UserEntity> userList = query.getResultList();
		return userList;
	}

    @Override
    public boolean updateUserActiveState(Long id, boolean active) {
        Query query = persistenceContext.createNamedQuery("updateUserActiveState");
        query.setParameter("active", active);
        query.setParameter("id", id);
        return query.executeUpdate()!=0;
    }

    @Override
    public boolean updateRole(Long id, Role roleEntity) {
         Query query = persistenceContext.createNamedQuery("updateUserRole");
        query.setParameter("role", roleEntity);
        query.setParameter("id", id);
        return query.executeUpdate()!=0;
    }

    @Override
    public void removeAll() {
        persistenceContext.createQuery("delete from " + UserEntity.class.getCanonicalName());
    }
}
